package main

import (
	"fmt"
	"net"
)

func readData(conn net.Conn) {
	// 关闭链接
	defer func(conn net.Conn) {
		err := conn.Close()
		if err != nil {
			fmt.Println("Error closing connection")
		}
	}(conn)

	clientConn := conn.RemoteAddr().String()
	fmt.Println("客户端 = ", clientConn)

	readBuf := make([]byte, 1024)
	readNum, err := conn.Read(readBuf)
	if err != nil {
		fmt.Println("Error reading from client")
		panic(err)
	}
	content := string(readBuf[:readNum])
	fmt.Println("接受到数据内容 -> ", content)
}

func main() {
	listener, err := net.Listen("tcp", "127.0.0.1:9999")
	if err != nil {
		panic(err)
	}
	fmt.Println("服务器启动成功 ，等待客户端连接 ... ")
	for {
		// 等待客户端的连接
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("Error accepting connection")
			panic(err)
		}
		go readData(conn)
	}
}
